
package com.foxit.pdf2html5.web.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.log4j.Logger;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.foxit.pdf2html5.web.common.Config;
import com.google.gson.JsonObject;

@Controller
@Scope("prototype")
public class LoginController{
	private static final Logger  log = Logger.getLogger(LoginController.class);

	@RequestMapping(value="/UserLogin.do")
	public static void Login(HttpServletRequest request,HttpServletResponse response) throws IOException{
        final HttpSession session = request.getSession(false);
        final Assertion assertion = (Assertion) (session == null ? request.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION) : session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION));
        String username = request.getParameter("USER_NAME");
 		String password = request.getParameter("PASSWORD");
 		String ssoURL = Config.HTML5EDITOR_SSO_URL_KEY; 
		String targetURL = Config.HTML5EDITOR_SELF_URL_KEY;
	     if(assertion == null) {
	    	 
	    	HttpClient httpClient = new HttpClient();
	 		try {
	 			//step1
	 			String r4TGT = ssoURL+"/v1/tickets/";
	 			String p4TGT = "username="+username+"&password="+password;
	 			InputStream  i4TGT = new ByteArrayInputStream(p4TGT.getBytes());
	 			RequestEntity requestEntity4TGT = new InputStreamRequestEntity(i4TGT, "text/html;charset=UTF-8");
	 			PostMethod postMethod4TGT = new PostMethod(r4TGT);
	 			postMethod4TGT.setRequestEntity(requestEntity4TGT);
	 			int statusCode4TGT = httpClient.executeMethod(postMethod4TGT);
	 			final Header tgtHeader = postMethod4TGT.getResponseHeader("Location");
	 			if(tgtHeader == null)
	 			{
	 				JsonObject json = new JsonObject();
	 				json.addProperty("success", String.valueOf(false));
	 				json.addProperty("msg", "Error username or password!");
	 				response.getWriter().write(json.toString());
	 				return;
	 			}
	 			
	 			//step2
	 			String param = "service="+URLEncoder.encode(targetURL,"utf-8");
	 			InputStream  in = new ByteArrayInputStream(param.getBytes());
	 			RequestEntity requestEntity = new InputStreamRequestEntity(in, "text/html;charset=UTF-8");
	 			
	 			PostMethod postMethod4Ticket = new PostMethod(tgtHeader.getValue().replaceFirst("http", "https"));
	 			postMethod4Ticket.setRequestEntity(requestEntity);
	 			int statusCode4Ticket = httpClient.executeMethod(postMethod4Ticket);
	 			final String response4Ticket = postMethod4Ticket.getResponseBodyAsString();
	 			if(statusCode4Ticket!=200){
	 			//	logger.error("get ticket fail return body."+response4Ticket);
	 				throw new RuntimeException("get ticket fail return statuscode."+statusCode4Ticket);
	 			}
	 			
	 			//step 3
	 			targetURL = targetURL+"?ticket="+response4Ticket;	
	 			response.sendRedirect(targetURL);
	 			
	 		/*	JsonObject json = new JsonObject();
		    	 json.addProperty("success", String.valueOf(true));
		    	 Assertion assertion2 = (Assertion) (session == null ? request.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION) : session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION));
		    	 AttributePrincipal ap = assertion2.getPrincipal();
		    	 String userId = (String)ap.getAttributes().get("id");
		    	 json.addProperty("userid",userId);
				 response.getWriter().write(json.toString());*/
				 return;
	 		} catch (Exception e) {
				e.printStackTrace();
				JsonObject json = new JsonObject();
				json.addProperty("success", String.valueOf(false));
				json.addProperty("msg", "Login Error!");
				response.getWriter().write(json.toString());
				return;
			}
	     }else{
	    	 JsonObject json = new JsonObject();
	    	 json.addProperty("success", String.valueOf(true));
	    	 AttributePrincipal ap = assertion.getPrincipal();
	    	 String userId = (String)ap.getAttributes().get("id");
	    	 Config.FOXIT_USER_ID_KEY = userId;
	    	 json.addProperty("userid",userId);
			 response.getWriter().write(json.toString());
			 return;
	     }
	}
	
	@RequestMapping(value="/UserLogout.do")
	public void Logout(HttpServletRequest request,HttpServletResponse response) throws IOException{
		final HttpSession session = request.getSession(false);
		session.removeAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
		session.invalidate();
		request.getSession().invalidate();
		JsonObject json = new JsonObject();
		 json.addProperty("success", String.valueOf(true));
		response.getWriter().write(json.toString());
		return;
	}
}
